package com.ece.demo.controller.commands.charactor;

import org.apache.commons.lang3.StringUtils;

import com.bulletphysics.dynamics.character.KinematicCharacterController;
import com.bulletphysics.linearmath.Transform;

import dev.ece.core.controller.Command;
import dev.ece.suit.loader.Sprite3D;
import dev.ece.util.lib.Matrix4f;
import dev.ece.util.lib.Vector3f;
import dev.ece.util.tools.Camera;

public abstract class SpriteMoveCommand extends Command {

	private Sprite3D<Float> sprite;
	
	private KinematicCharacterController controller;
	
	private Camera camera;
	
	private float speed;
	
	public SpriteMoveCommand(Sprite3D<Float> sprite, KinematicCharacterController controller, Camera camera, float speed) {
		this.sprite = sprite;
		this.controller = controller;
		this.camera = camera;
		this.speed = speed;
	}
	
	@Override
	public void onExecute() {
		if(!StringUtils.startsWith(sprite.getActionName(), "move")) {
			sprite.action("move-1");
		}
		Vector3f dir = this.getDirVector();
		controller.setWalkDirection(dir.toVector3f());
		
		Transform transform = new Transform();
		sprite.getJbulletTransformation().getCollisionObject().getWorldTransform(transform);
		Vector3f position = Vector3f.from(transform.origin);
		
		//调整摄像机
		this.camera.setPosition(position.getX(), position.getY() + 1, position.getZ());
		
		Matrix4f matrix = new Matrix4f();
		matrix.identity();
		matrix.rotate(-1f, 0, 0, 45);
		
		this.camera.center.splus(this.camera.position, this.camera.center);
		matrix.transform(this.camera.center);
		this.camera.center.add(this.camera.position);
		matrix.transform(this.camera.head);
		
		float distance = 2f;
		//前进方向相反的向量
		Vector3f vector = new Vector3f();
		vector.splus(this.camera.center, this.camera.position);
		vector.normalize();
		vector.setLength(distance);
		this.camera.position.add(vector);
		this.camera.center.add(vector);
	}

	@Override
	public void onKeyPress() {
		
	}

	@Override
	public void onKeyRelease() {
		sprite.action("stand-1");
		controller.setWalkDirection(new Vector3f().toVector3f());
	}
	
	public abstract Vector3f getDirVector();

	public Sprite3D<Float> getSprite() {
		return sprite;
	}

	public KinematicCharacterController getController() {
		return controller;
	}

	public Camera getCamera() {
		return camera;
	}

	public float getSpeed() {
		return speed;
	}

}
